package com.liuyk.util;

import android.os.Environment;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.io.OutputStream;
import java.io.Serializable;

/**
 * 序列化工具
 * Created by liuyakui on 2015/9/11.
 */
public class SerializableUtil {

    public static <T> File serializableObject(T t, String fileName) {
        if (!(t instanceof Serializable)) {
            throw new IllegalArgumentException("The second parameter is not valid");
        }
        ObjectOutputStream oos = null;
        FileOutputStream fos = null;
        File file = null;
        try {
            file = new File(Environment.getExternalStorageDirectory(), fileName);
            if (file.exists()) {
                file.delete();
            }
            fos = new FileOutputStream(file);
            oos = new ObjectOutputStream(fos);
            oos.writeObject(t);
        } catch (IOException e) {
            file = null;
        } finally {
            closeOutputStream(fos, oos);
        }
        return file;
    }

    public static <T> T deSerializable(String fileName) {
        FileInputStream fis = null;
        ObjectInputStream ois = null;
        File file = new File(Environment.getExternalStorageDirectory(), fileName);
        T t;
        if (!file.exists()) {
            t = null;
        } else {
            try {
                fis = new FileInputStream(file);
                ois = new ObjectInputStream(fis);
                t = (T) ois.readObject();
            } catch (Exception e) {
                t = null;
            } finally {
                closeInputStream(fis, ois);
            }
        }
        return t;
    }

    private static void closeInputStream(InputStream... is) {
        for (InputStream inputStream : is) {
            if (inputStream != null) {
                try {
                    inputStream.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }

    }

    private static void closeOutputStream(OutputStream... os) {
        for (OutputStream outputStream : os) {
            if (outputStream != null) {
                try {
                    outputStream.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
    }

}
